package top.houry.netty.barrage.netty;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import top.houry.netty.barrage.consts.BarrageRedisKeyConst;
import top.houry.netty.barrage.utils.BarrageRedisUtils;

import java.net.InetSocketAddress;

/**
 * @Desc Ip过滤器自定义设置
 * @Author houruiyang
 * @Date 2021/11/27
 **/
@Slf4j
public class WebSocketNettyServerRuntimeIpFilterHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        String rejectCache = BarrageRedisUtils.get(BarrageRedisKeyConst.BARRAGE_SERVER_REJECT_CONNECT_KEY + clientIp);
        if (StrUtil.isNotBlank(rejectCache)) {
            log.info("WebSocketNettyServerIpFilterHandler-channelRead-ip:{}-黑名单-访问直接断开", clientIp);
            ctx.channel().close();
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
